package com.haidechizi.i18n.code.generator.common.dynamic.generator;

import com.google.common.collect.Lists;
import com.haidechizi.i18n.code.generator.common.dynamic.enums.I18nTypeEnum;
import com.haidechizi.i18n.code.generator.common.dynamic.param.DynamicI18nConfig;
import com.haidechizi.i18n.code.generator.common.message.utils.FileTypeUtils;
import com.haidechizi.i18n.code.generator.common.message.utils.FileUtils;
import com.haidechizi.i18n.code.generator.common.message.utils.StringUtils;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DefaultDynamicCodeGenerator implements DynamicCodeGenerator {

    private static final String fileType = "java";

    private static final String importRegex = "^package.*";

    private static final String classRegex = "(public\\s+class\\s+([A-Z0-9a-z]+).*)\\{";


    private static final List<String> fieldRegexList = Lists.newArrayList("private\\s+String\\s+([a-z0-9A-Z_]+);",
            "private\\s+Map[<a-z0-9A-Z_>,\\s]+\\s+([a-z0-9A-Z_]+).*;", "private\\s+List[<a-z0-9A-Z_>,\\s]+\\s+([a-z0-9A-Z_]+).*;");

    /**
     * 根据文件路径获取所有可国际化的字段
     *
     * @param i18nConfig
     * @return
     */
    @Override
    public DynamicI18nConfig getI18nField(DynamicI18nConfig i18nConfig) {
        File file = new File(i18nConfig.getFilePath());
        if (!file.isFile()) {
            throw new RuntimeException("不是文件");
        }
        String fileSuffix = FileTypeUtils.fileSuffix(i18nConfig.getFilePath());
        if (!fileType.equals(fileSuffix)) {
            throw new RuntimeException("不是java文件");
        }
        // 读取文件内容
        String content = FileUtils.readFile(i18nConfig.getFilePath());

        // 读取class
        Pattern classPattern = Pattern.compile(classRegex);
        Matcher classMatcher = classPattern.matcher(content);
        if (classMatcher.find()) {
            String code = getCode(i18nConfig, classMatcher.group(2));
            i18nConfig.setBusinessCode(code);
            i18nConfig.setI18nModelReplacePattern(classMatcher.group(1));

        }

        // 读取所有的field
        for (String regex : fieldRegexList) {
            Pattern fieldPattern = Pattern.compile(regex);
            Matcher fieldMatcher = fieldPattern.matcher(content);
            while (fieldMatcher.find()) {
                String fieldName = fieldMatcher.group(1);
                String code = getCode(i18nConfig, fieldName);
                String i18nFieldReplacePattern = fieldMatcher.group();
                i18nFieldReplacePattern = i18nFieldReplacePattern.replaceAll("\\(", "\\\\(")
                        .replaceAll("\\)", "\\\\)");
//                .replaceAll("<","\\<")
//                .replaceAll(">","\\>");
                DynamicI18nConfig.I18nFieldConfig i18nFieldConfig = new DynamicI18nConfig.I18nFieldConfig(code, i18nFieldReplacePattern);
                i18nConfig.addI18nField(i18nFieldConfig);
            }
        }

        return i18nConfig;
    }

    /**
     * 根据用户选择的字段创建文件
     *
     * @param i18nConfig
     */
    @Override
    public void generatorFile(DynamicI18nConfig i18nConfig) {
        // 是否生成备份文件
        if (i18nConfig.isBackupFile()) {
            FileUtils.copyFile(i18nConfig.getFilePath(), ".bak");
        }
        // 读取文件内容
        String content = FileUtils.readFile(i18nConfig.getFilePath());

        // 1.在类上添加注解
        Pattern classPattern = Pattern.compile(i18nConfig.getI18nModelReplacePattern());
        Matcher classMatcher = classPattern.matcher(content);
        if (classMatcher.find()) {
            String group = classMatcher.group();
            StringBuilder sb = new StringBuilder();
            sb.append("@I18nModel(systemCode = \"").append(i18nConfig.getSystemCode()).append("\"")
                    .append(", businessCode = \"").append(i18nConfig.getBusinessCode()).append("\"");
            if (!"id".equals(i18nConfig.getBusinessKey())) {
                sb.append(", businessKey = \"").append(i18nConfig.getBusinessKey()).append("\"");
            }
            sb.append(")\n");
            sb.append(group);

            content = content.replace(group, sb.toString());

            // import class
            Pattern importPattern = Pattern.compile(importRegex);
            Matcher importMatcher = importPattern.matcher(content);
            if (importMatcher.find()) {
                String group1 = importMatcher.group();
                StringBuilder importSb = new StringBuilder();
                importSb.append(group1).append("\n").append("import com.haidechizi.i18n.common.annotation.I18nModel;");
                content = content.replace(group1, importSb.toString());
            }

        }

        boolean importI18nField = false;

        // 在field上添加注解
        for (DynamicI18nConfig.I18nFieldConfig fieldConfig : i18nConfig.getConfigList()) {
            if (!fieldConfig.isTranslate()) {
                continue;
            }
            Pattern pattern = Pattern.compile(fieldConfig.getI18nFieldReplacePattern());
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                String group = matcher.group();
                String replaceData = replaceFieldData(group, fieldConfig);
                content = content.replace(group, replaceData);
                importI18nField = true;
            }
        }

        // import I18nField
        if (importI18nField) {
            // import class
            Pattern importPattern = Pattern.compile(importRegex);
            Matcher importMatcher = importPattern.matcher(content);
            if (importMatcher.find()) {
                String group1 = importMatcher.group();
                StringBuilder importSb = new StringBuilder();
                importSb.append(group1).append("\n").append("import com.haidechizi.i18n.common.annotation.I18nField;");
                content = content.replace(group1, importSb.toString());
            }
        }

        // 生成新的文件
        if (i18nConfig.isGenerateNewFile()) {
            FileUtils.createFile(content, i18nConfig.getFilePath(), ".new");
        }

        // 是否替换原
        if (i18nConfig.isReplaceFile()) {
            FileUtils.createFile(content, i18nConfig.getFilePath(), "");
        }

    }

    private String replaceFieldData(String group, DynamicI18nConfig.I18nFieldConfig fieldConfig) {
        StringBuilder sb = new StringBuilder();
        if (I18nTypeEnum.SIMPLE.getType() == fieldConfig.getI18nType()) {
            sb.append("@I18nField(value = \"").append(fieldConfig.getValue()).append("\")");
        } else if (I18nTypeEnum.COMBINED.getType() == fieldConfig.getI18nType()) {
            sb.append("@I18nField(systemCode = \"").append(fieldConfig.getSystemCode()).append("\"")
                    .append(", businessCode = \"").append(fieldConfig.getBusinessCode()).append("\"");
            if (!"id".equals(fieldConfig.getBusinessKey())) {
                sb.append(", businessKey = \"").append(fieldConfig.getBusinessKey()).append("\"");
            }
            sb.append(", value = \"").append(fieldConfig.getValue()).append("\")");

        } else {
            sb.append("@I18nField(metaCalculator = \"").append(fieldConfig.getMetaCalculator()).append("\")");
        }
        sb.append("\n    ").append(group);
        return sb.toString();
    }

    private String getCode(DynamicI18nConfig dynamicI18nConfig, String code) {
        // 使用下划线方式命名
        if ("1".equals(dynamicI18nConfig.getKeyGeneratorType())) {
            return StringUtils.toUnderScoreCase(code);
        }
        return code;
    }
}
